//
//  SendStatuesViewController.m
//  新浪微博
//
//  Created by hbl on 16/2/29.
//  Copyright © 2016年 hbl. All rights reserved.
//

#import "SendStatuesViewController.h"
#import "AFNetworking.h"
#import "Access.h"
#import "AccessTool.h"
#import "MBProgressHUD+MJ.h"  
#import "SendToolBar.h"
#import "BLTextView.h"
@interface SendStatuesViewController ()<SendToolBarDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic, weak)BLTextView *text;
@property (nonatomic, weak)SendToolBar *sendBar;
@property (nonatomic, weak)UIImage *sendPhotoImage;
@end

@implementation SendStatuesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupTitleBar];
    
    [self setupText];
    
    [self setupSendToolBar];
    
    [self setupKeyBoard];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationItem.rightBarButtonItem.enabled = NO;
}

- (void)setupTitleBar
{
    self.title = @"发微博";
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStyleDone target:self action:@selector(send)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    }

- (void)setupText
{
    BLTextView *text = [[BLTextView alloc]init];
    text.frame = self.view.bounds;
    text.font = [UIFont systemFontOfSize:19];
    [self.view addSubview:text];
    self.text = text;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:text];
}

- (void)textChange
{
    self.navigationItem.rightBarButtonItem.enabled = !(self.text.text.length == 0);
}

- (void)setupSendToolBar
{
    SendToolBar *sendBar = [[SendToolBar alloc]init];
    sendBar.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 44, [UIScreen mainScreen].bounds.size.width, 44);
    [sendBar addToolButtonWithImageName:@"compose_toolbar_picture_os7" selImageNmae:@"compose_toolbar_picture_highlighted_os7"];
    [sendBar addToolButtonWithImageName:@"compose_camerabutton_background_os7" selImageNmae:@"compose_camerabutton_background_highlighted_os7"];
    [sendBar addToolButtonWithImageName:@"compose_trendbutton_background_os7" selImageNmae:@"compose_trendbutton_background_highlighted_os7"];
    [sendBar addToolButtonWithImageName:@"compose_mentionbutton_background_os7" selImageNmae:@"compose_mentionbutton_background_highlighted_os7"];
    [self.view addSubview:sendBar];
    sendBar.delegate = self;
    self.sendBar = sendBar;
}

- (void)setupSendImage
{
    UIImageView *sendImageView = [[UIImageView alloc]initWithImage:self.sendPhotoImage];
    sendImageView.frame = CGRectMake(10, 200, 100, 100);
    [self.text addSubview:sendImageView];
}

- (void)setupKeyBoard
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyBoardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)onKeyBoardChange:(NSNotification *)info
{
   
    NSDictionary *keyBoadInfo = info.userInfo;
    CGRect keyBoardRect = [keyBoadInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    CGFloat deltaY = keyBoardRect.origin.y - self.view.bounds.size.height;
    [UIView animateWithDuration:0.25 animations:^{
        self.sendBar.transform = CGAffineTransformMakeTranslation(0, deltaY);
    }];
    
}

- (void)send
{
    if (!self.sendPhotoImage) {
        Access *access = [[Access alloc]init];
        access = [AccessTool getTheAccess];
        NSString *token = access.access_token;
        
        NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/2/statuses/update.json"];
        
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
        request.HTTPMethod = @"POST";
        
        NSString *param = [NSString stringWithFormat:@"access_token=%@&status=%@",token,self.text.text];
        
        request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (!error) {
                
                if ([self.delegate respondsToSelector:@selector(sendStatuesIsSeccess:)]) {
                    [self.delegate sendStatuesIsSeccess:YES];
                }
                
                
            }else{
                if ([self.delegate respondsToSelector:@selector(sendStatuesIsSeccess:)]) {
                    [self.delegate sendStatuesIsSeccess:NO];
                }
                
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        [task resume];

    }else{
        [self sendImage];
    }
}

- (void)sendImage
{
    Access *access = [[Access alloc]init];
    access = [AccessTool getTheAccess];
    NSString *token = access.access_token;
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = token;
    parameters[@"status"] = self.text.text;
   
   [manager POST:@"https://upload.api.weibo.com/2/statuses/upload.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:UIImageJPEGRepresentation(self.sendPhotoImage, 0.7) name:@"pic" fileName:@"hbl1.jpeg" mimeType:@"image/jpeg"];
    } progress:nil
      success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         
          if ([self.delegate respondsToSelector:@selector(sendStatuesIsSeccess:)]) {
              [self.delegate sendStatuesIsSeccess:YES];
          }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        if ([self.delegate respondsToSelector:@selector(sendStatuesIsSeccess:)]) {
            [self.delegate sendStatuesIsSeccess:NO];
        }
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)sendToolBarClickBtn:(UIButton *)btn
{
    switch (btn.tag) {
        case 0:
            [self openPhotoLibrary];
            break;
           
        case 1:
            [self openCamera];
            break;
        default:
            break;
    }
}


- (void)openCamera
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)openPhotoLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
     picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = info[@"UIImagePickerControllerOriginalImage"];
    self.sendPhotoImage = image;
    [self setupSendImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
